package com.zjeav.lingjiao.ui.login;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dalimao.corelibrary.view.LoadProgressDialog;
import com.dalimao.corelibrary.view.SelfDialog;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.QQTools.Util;
import com.zjeav.lingjiao.base.baseBean.BaseApplication;
import com.zjeav.lingjiao.base.baseBean.PermissionListener;
import com.zjeav.lingjiao.base.config.BaseConfig;
import com.zjeav.lingjiao.base.listener.CallBackTypeInteraction;
import com.zjeav.lingjiao.base.request.LoginRequest;
import com.zjeav.lingjiao.base.request.OtherLoginRequest;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.utils.CheckPermissionsActivity;
import com.zjeav.lingjiao.base.utils.StringUtils;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.home.RestructureMainActivity;
import com.zjeav.lingjiao.ui.personCenter.ModifyPasswordActivity;
import com.zjeav.lingjiao.ui.register.RegisterPhoneActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LoginActivty extends CheckPermissionsActivity implements View.OnClickListener,
        LoginContract.View, IUiListener, CallBackTypeInteraction {

    EditText username_ed;
    EditText pw_ed;
    Button login_bn;
    TextView forget_txt;
    TextView register_tex;
    TextView qq_login_txt;
    TextView wx_login_txt;
    UserPresenter userPresenter;
    private Tencent mTencent;

    public PermissionListener mPermissionListener;
    private LoadProgressDialog loadProgressDialog; //加载框
    private static final String APP_ID = "wxd7c954bd04cef4dc";
    private IWXAPI api;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        login_bn = findViewById(R.id.login_bn);
        forget_txt = findViewById(R.id.forget_txt);
        register_tex = findViewById(R.id.register_tex);
        qq_login_txt = findViewById(R.id.qq_login_txt);
        wx_login_txt = findViewById(R.id.wx_login_txt);
        username_ed = findViewById(R.id.username_ed);
        pw_ed = findViewById(R.id.pw_ed);
        login_bn.setOnClickListener(this);
        forget_txt.setOnClickListener(this);
        register_tex.setOnClickListener(this);
        qq_login_txt.setOnClickListener(this);
        wx_login_txt.setOnClickListener(this);
        UserPresenter.setBRInteractionListener(this);

        login_bn.setClickable(false);

        loadProgressDialog = new LoadProgressDialog(this, com.dalimao.corelibrary.R.style.MyDialog);

        initData();
        regToWx();
        mTencent = Tencent.createInstance(BaseConfig.QQ_APP_ID, this);

        String wechatlogin = SharedPreferencesUtils.getParam(this, "wechatlogin", "").toString();

        if ("0".equals(wechatlogin)) {
            SharedPreferencesUtils.setParam(this, "weChat", 0);
            WXlogin();
        }


    }

    private void regToWx() {
        api = WXAPIFactory.createWXAPI(this, BaseConfig.APP_ID, true);
        api.registerApp(BaseConfig.APP_ID);
    }

    private void WXlogin() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "com_zjeav_lingjiao";
//        req.appid="wxd7c954bd04cef4dc";
        api.sendReq(req);
        finish();
    }

    private void initData() {
        userPresenter = new UserPresenter(this);
        SharedPreferencesUtils.setParam(this, "isLogin", false);
        String username = SharedPreferencesUtils.getParam(this, "username", "").toString();
        String password = SharedPreferencesUtils.getParam(this, "password", "").toString();

        if (!"".equals(username)) {
            username_ed.setText(username);
        }
        if (!"".equals(password)) {
            pw_ed.setText(password);
        }

        if (!StringUtils.isNullOrEmpty(username) && !StringUtils.isNullOrEmpty(password)) {
            login_bn.setClickable(true);
            login_bn.setBackground(getResources().getDrawable(R.drawable.buttonstyle));
        }

        pw_ed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                login_bn.setBackground(getResources().getDrawable(R.drawable.buttonunableclickstyle));
                login_bn.setClickable(false);

                if (charSequence.length() > 0) {
                    String strusername = username_ed.getText().toString();
                    if (!StringUtils.isNullOrEmpty(strusername)) {
                        login_bn.setClickable(true);
                        login_bn.setBackground(getResources().getDrawable(R.drawable.buttonstyle));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        username_ed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                login_bn.setBackground(getResources().getDrawable(R.drawable.buttonunableclickstyle));
                login_bn.setClickable(false);

                if (charSequence.length() > 0) {
                    String strpassword = pw_ed.getText().toString();
                    if (!StringUtils.isNullOrEmpty(strpassword)) {
                        login_bn.setClickable(true);
                        login_bn.setBackground(getResources().getDrawable(R.drawable.buttonstyle));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, this);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onComplete(Object o) {
        if (null == o) {
            Util.showResultDialog(LoginActivty.this, "返回为空", "登录失败");
            return;
        }
        JSONObject jsonResponse = (JSONObject) o;
        if (null != jsonResponse && jsonResponse.length() == 0) {
            Util.showResultDialog(LoginActivty.this, "返回为空", "登录失败");
            return;
        }
        OtherLoginRequest request = null;
        try {
            request = new OtherLoginRequest(jsonResponse.get("access_token").toString(), jsonResponse.get("openid").toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        userPresenter.QQLogin(request);
    }

    @Override
    public void onError(UiError uiError) {
        Util.toastMessage(LoginActivty.this, "onError: " + uiError.errorDetail);
        Util.dismissDialog();
    }

    @Override
    public void onCancel() {
        Util.toastMessage(LoginActivty.this, "onCancel: ");
        Util.dismissDialog();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_bn:
                if (username_ed.getText().toString().equals("")) {
                    Toast.makeText(this, "请输入手机/邮箱", Toast.LENGTH_SHORT).show();
                } else if (pw_ed.getText().toString().equals("")) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                } else {
                    loadProgressDialog.show();
                    SharedPreferencesUtils.setParam(this, "wechatlogin", "1");
                    LoginRequest request = new LoginRequest(username_ed.getText().toString(), pw_ed.getText().toString(), BaseApplication.deviceInfo);
                    userPresenter.login(request);
                }
                break;
            case R.id.qq_login_txt:
                mTencent.login(this, "all", this, true);
                break;
            case R.id.wx_login_txt:
                SharedPreferencesUtils.setParam(this, "weChat", 0);
                WXlogin();
                break;
            case R.id.forget_txt: //忘记密码
                Intent intent3 = new Intent(this, ModifyPasswordActivity.class);
                intent3.putExtra("titlename", "忘记密码");
                startActivityForResult(intent3, 3);
                break;
            case R.id.register_tex:
                Intent intent = new Intent(this, RegisterPhoneActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void showError(Throwable throwable) {
        loadProgressDialog.dismiss();
        UIUtils.showToast("登陆失败");
    }

    @Override
    public void skipActivity() {
        Intent intent = new Intent(this, RestructureMainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void dissDiagle() {
        if (MProgressDialog.isShowing()) {
            MProgressDialog.dismissProgress();
        }
        SharedPreferencesUtils.setParam(this, "username", username_ed.getText().toString());
        SharedPreferencesUtils.setParam(this, "password", pw_ed.getText().toString());
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void callBackType(String type) {
        loadProgressDialog.dismiss();
        final SelfDialog selfDialog = new SelfDialog(this);
        selfDialog.setTitle("登录失败");
        selfDialog.setMessage("账号或密码错误，请重新输入");
        selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                selfDialog.dismiss();
            }
        });
        selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                selfDialog.dismiss();
            }
        });
        selfDialog.show();
    }

    @Override
    public void callBackType(String type, Intent intent) {

    }

    /**
     * 申请运行时权限
     */
    public void requestRuntimePermission(String[] permissions, PermissionListener permissionListener) {
        mPermissionListener = permissionListener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            permissionListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedPermissions.add(permission);
                        }
                    }
                    if (deniedPermissions.isEmpty()) {
                        mPermissionListener.onGranted();
                    } else {
                        mPermissionListener.onDenied(deniedPermissions);
                    }
                }
                break;
        }
    }
}
